import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class DataManager {
  // 内存存储（代替数据库）
  static List<User> users = new ArrayList<>();
  static List<Movie> movies = new ArrayList<>();
  static List<Seat> seats = new ArrayList<>();
  static List<Order> orders = new ArrayList<>();
  static List<Feedback> feedbacks = new ArrayList<>();
  static List<Schedule> schedules = new ArrayList<>();

  // 密码哈希
  static String hashPassword(String password) {
      try {
          MessageDigest md = MessageDigest.getInstance("SHA-256");
          byte[] hashedBytes = md.digest(password.getBytes());
          StringBuilder sb = new StringBuilder();
          for (byte b : hashedBytes) {
              sb.append(String.format("%02x", b));
          }
          return sb.toString();
      } catch (NoSuchAlgorithmException e) {
          throw new RuntimeException("Error hashing password", e);
      }
  }

  // 保存数据
  static void saveData() {
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("moviedata.ser"))) {
          oos.writeObject(users);
          oos.writeObject(movies);
          oos.writeObject(seats);
          oos.writeObject(orders);
          oos.writeObject(feedbacks);
          oos.writeObject(schedules);
      } catch (IOException e) {
          System.out.println("保存数据失败: " + e.getMessage());
      }
  }

  // 加载数据
  @SuppressWarnings("unchecked")
  static void loadData() {
      File file = new File("moviedata.ser");
      if (file.exists()) {
          try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("moviedata.ser"))) {
              users = (List<User>) ois.readObject();
              movies = (List<Movie>) ois.readObject();
              seats = (List<Seat>) ois.readObject();
              orders = (List<Order>) ois.readObject();
              feedbacks = (List<Feedback>) ois.readObject();
              schedules = (List<Schedule>) ois.readObject();
          } catch (IOException | ClassNotFoundException e) {
              System.out.println("加载数据失败，将使用初始数据: " + e.getMessage());
              initializeSampleData();
          }
      } else {
          initializeSampleData();
      }
  }

  // 初始化示例数据
  static void initializeSampleData() {
      // 添加默认管理员账户（如果不存在）
      if (users.stream().noneMatch(u -> u.role == UserRole.ADMIN)) {
          users.add(new User(users.size() + 1, "admin", hashPassword("admin123"), 
                   "系统管理员", "13800000000", "admin@cinema.com", UserRole.ADMIN));
      }

      // 添加默认售票员账户
      if (users.stream().noneMatch(u -> u.username.equals("sales1"))) {
          users.add(new User(users.size() + 1, "sales1", hashPassword("sales123"), 
                   "售票员张三", "13800000001", "sales1@cinema.com", UserRole.SALES));
      }

      // 添加默认店长账户
      if (users.stream().noneMatch(u -> u.username.equals("manager1"))) {
          users.add(new User(users.size() + 1, "manager1", hashPassword("manager123"), 
                   "店长李四", "13800000002", "manager1@cinema.com", UserRole.MANAGER));
      }

      // 添加电影
      if (movies.isEmpty()) {
          movies.add(new Movie(1, "流浪地球", "郭帆", "吴京,屈楚萧", 125, "科幻冒险", 45.0));
          movies.add(new Movie(2, "哪吒之魔童降世", "饺子", "吕艳婷,囧森瑟夫", 110, "动画电影", 40.0));
      }

      // 添加排片
      if (schedules.isEmpty()) {
          Calendar cal = Calendar.getInstance();
          cal.add(Calendar.HOUR, 2);
          schedules.add(new Schedule(1, 1, new Date(), cal.getTime(), "1号厅"));
          cal.add(Calendar.HOUR, 4);
          schedules.add(new Schedule(2, 2, new Date(), cal.getTime(), "2号厅"));
      }

      // 添加座位（假设每个排片有5排10列）
      if (seats.isEmpty()) {
          for (Schedule schedule : schedules) {
              for (int row = 1; row <= 5; row++) {
                  for (int col = 1; col <= 10; col++) {
                      seats.add(new Seat(seats.size() + 1, row, col, true, schedule.id));
                  }
              }
          }
      }
  }

  // 根据ID获取电影
  static Movie getMovieById(int id) {
      for (Movie movie : movies) {
          if (movie.id == id) {
              return movie;
          }
      }
      return null;
  }

  // 根据ID获取排片
  static Schedule getScheduleById(int id) {
      for (Schedule schedule : schedules) {
          if (schedule.id == id) {
              return schedule;
          }
      }
      return null;
  }

  // 根据电影ID获取排片
  static List<Schedule> getSchedulesByMovieId(int movieId) {
      List<Schedule> result = new ArrayList<>();
      for (Schedule schedule : schedules) {
          if (schedule.movieId == movieId) {
              result.add(schedule);
          }
      }
      return result;
  }

  // 根据ID获取座位
  static Seat getSeatById(int id) {
      for (Seat seat : seats) {
          if (seat.id == id) {
              return seat;
          }
      }
      return null;
  }

  // 根据ID获取用户
  static User getUserById(int id) {
      for (User user : users) {
          if (user.id == id) {
              return user;
          }
      }
      return null;
  }

  // 查找座位
  static Seat findSeat(int scheduleId, int row, int col) {
      for (Seat seat : seats) {
          if (seat.scheduleId == scheduleId && seat.row == row && seat.col == col) {
              return seat;
          }
      }
      return null;
  }

  // 解析日期
  static Date parseDate(String dateStr) {
      try {
          return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateStr);
      } catch (Exception e) {
          return null;
      }
  }
}